package demo2;

import demo.Thread2;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * Remarks:
 * Class name :CallableTest
 * Date :2023/2/13 23:10
 * Author:杨俊源
 */
public class CallableTest implements Callable<Boolean> {

    private String url;
    private String name;

    public CallableTest(String url,String name){
        this.url = url;
        this.name = name;
    }
    @Override

    public Boolean call() {
        WebDownLoader webDownLoader = new WebDownLoader();
        webDownLoader.download(url, name);
        System.out.println("download  name = " + name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CallableTest thread1 = new CallableTest("https://img1.baidu.com/it/u=3306572176,704436528&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500", "1.jpg");
        CallableTest thread2 = new CallableTest("https://img1.baidu.com/it/u=3306572176,704436528&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500", "2.jpg");
        CallableTest thread3 = new CallableTest("https://img1.baidu.com/it/u=3306572176,704436528&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500", "3.jpg");

        ExecutorService service = Executors.newFixedThreadPool(3);
        Future<Boolean> r1 = service.submit(thread1);
        Future<Boolean> r2 = service.submit(thread2);
        Future<Boolean> r3 = service.submit(thread3);

        Boolean rs1 = r1.get();
        Boolean rs2 = r2.get();
        Boolean rs3 = r3.get();

        System.out.println("rs1 = " + rs1);
        System.out.println("rs2 = " + rs2);
        System.out.println("rs3 = " + rs3);
        service.shutdownNow();
    }
}

class WebDownLoader {
    public void download(String url, String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常");
        }
    }
}

